package com.gds.controller;

import com.gds.aspect.LogInfo;
import com.gds.common.wechat.AccessTokenWechatHttpResult;
import com.gds.common.wechat.UserInfoWechatHttpResult;
import com.gds.common.wechat.WechatUtils;
import com.gds.common.wechat.wechat.WxJSUtil;
import com.gds.common.wechat.wechat.entities.Oauth2AccessTokenResult;
import com.gds.common.wechat.wechat.httpRequest.WechatOath2HttpRequest;
import com.gds.service.WechatService;
import com.gds.service.impl.WxProperties;
import com.gds.utils.BizException;
import com.gds.utils.BizExceptionUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;


@Controller
@RequestMapping("/wechatH5")
public class WechatH5Controller {

    private String appid = "wx73d3293bf34128b2";
    private final String secret = "2ddcc6b32896b73b19162f9c534a858a";
    @Autowired
    private WxProperties wxProperties;
    @Autowired
    private WechatService wechatService;


    @RequestMapping("/wxToken")
    @ResponseBody
    public void wxToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // / 微信加密签名
        String signature = request.getParameter("signature");
        // / 时间戳
        String timestamp = request.getParameter("timestamp");
        // / 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        PrintWriter printWriter = response.getWriter();
        if (WxJSUtil.checkSignature(wxProperties.getToken(), signature, timestamp, nonce)) {
            printWriter.print(echostr);
            System.out.println("========微信认证token成功========= ");
        } else {
            System.out.println("========微信认证token失败========= ");
        }
        printWriter.flush();
        printWriter.close();

    }

    /***
     * 获取授权登录页
     *  扫码微信授权
     * @param  merchantId 商户码
     * @param response
     * @throws IOException
     */
    @RequestMapping("/wechatLogin")
    public void getWechatUser(@RequestParam("merchantId") String merchantId,
                              @RequestParam("tableId") String tableId,
                              HttpServletResponse response

    ) throws IOException {
        String response_type = "code";
        String scope = "snsapi_base";
        String state = "state";
        //拼接 登录 url
        response.sendRedirect(
                WechatOath2HttpRequest.toWechantLogin(
                        wxProperties.getAppId(),
                        wxProperties.getBaseUrl() + "/wechatH5/getAccessToken?merchantId=" + merchantId + "&tableId=" + tableId,
                        response_type,
                        scope,
                        state)
        );
    }

    /***
     * 通过code获取用户信息(openId)
     * @param code  微信返回的code
     * @return
     */
    @RequestMapping("/getAccessToken")
    public void getAccessToken(@RequestParam("code") String code,
                               @RequestParam("merchantId") String merchantId,
                               @RequestParam("tableId") String tableId,
                               HttpServletRequest request,
                               HttpServletResponse response) throws IOException {
        Map<String,Object> result = new LinkedHashMap<>(4);
        Oauth2AccessTokenResult accessToken = wechatService.getAccessToken(code);
        if (accessToken == null) {
            result.put("merchantId", merchantId);
            result.put("tableId", tableId);
            result.put("errno", "416");
            result.put("msg", URLEncoder.encode("请重新扫码登录","UTF-8"));
        }
        request.getSession().removeAttribute("accessToken");
        request.getSession().setAttribute("accessToken", accessToken);

        result.put("merchantId", merchantId);
        result.put("tableId", tableId);
        result.put("errno","200");
        result.put("msg",  URLEncoder.encode("授权成功","UTF-8"));

        //跳转前端页面
        response.sendRedirect(WechatOath2HttpRequest.getUrl(wxProperties.getBaseUrl()+wxProperties.getRedirect(),result,"授权登录跳转页面"));
    }

    /***
     * 获取微信js-sdk配置
     * @param redirectUri
     * @return
     */
    @LogInfo(operationDesc = "获取微信js-sdk配置")
    @RequestMapping("/getJsConfig")
    @ResponseBody
    public Map<String, Object> getJsConfig(@RequestParam("redirectUri") String redirectUri) {
        BizExceptionUtils.isEmpty(redirectUri,"url不能为空",true);
        return wechatService.getJsConfig(wxProperties.getBaseUrl() + redirectUri);

    }


}
